/*
 * Datagrid
 * widthClass (ui-column-xxlarge, ui-column-xlarge, ui-column-large, ui-column-medium, ui-column-small, ui-column-mini)
 */

define(function (require, exports, module) {





	var THTpl = require("./THTpl.html");
	var TDTpl = require("./TDTpl.html");


	var tpl = require("./tpl.html");
	Handlebars.registerHelper('isData', function (type, options) {
		if (type == "data") {
			return options.fn(this);
		}
	});
	Handlebars.registerHelper('isCheckbox', function (type, options) {
		if (type == "checkbox") {
			return options.fn(this);
		}
	});
	Handlebars.registerHelper('isCommand', function (type, options) {
		if (type == "command") {
			return options.fn(this);
		}
	});
	Handlebars.registerHelper('isColor', function (type, options) {
		if (type == "color") {
			return options.fn(this);
		}
	});
	var setColumnTpl = require("./setColumnTpl.html");

	var THTemplate = Handlebars.compile(THTpl);
	var TDTemplate = Handlebars.compile(TDTpl);
	var setColumnTemplage = Handlebars.compile(setColumnTpl);


	var defaultColumn = function (type) {
		var column = {};
		column["data"] = {
			type: "data",
			isShow: true,
			widthClass: "ui-column-small",
			sortable: false,
			property: "",               // 数据绑定字段
			sortProperty: "",           // 数据排序排序字段
			label: "",                  // 列头标题
			commandName: "",            // 事件名称
			classes: "",
			title: null,                   // 鼠标移动到数据上显示的,
			id: "",                     // 列id,有property就用property,没有就自己造
			num: 0                      // 列排序字段
		};
		column["checkbox"] = {
			type: "checkbox",
			isShow: true,
			widthClass: "ui-column-mini",
			sortable: false,
			label: "选择",
			property: "",
			sortProperty: "",
			commandName: "",
			classes: "",
			title: null,
			id: "",                     // 列id,有property就用property,没有就自己造
			num: 0                      // 列排序字段
		};
		column["command"] = {
			type: "command",
			isShow: true,
			widthClass: "ui-column-mini",
			sortable: false,
			label: "操作",
			commandName: "set",
			property: "",
			sortProperty: "",
			classes: "",
			title: null,
			id: "",                     // 列id,有property就用property,没有就自己造
			num: 0                      // 列排序字段
		};
		column["color"] = {
			type: "color",
			isShow: true,
			widthClass: "ui-colunm-mini",
			sortable: false,
			label: "",
			property: "",
			sortProperty: "",
			commandName: "",
			classes: "",
			title: null,
			id: "",                     // 列id,有property就用property,没有就自己造
			num: 0                      // 列排序字段
		};
		return column[type];
	};

	// DATAGRID CONSTRUCTOR AND PROTOTYPE

	var Datagrid = function (element, options) {

		var self = this;
		this.options = options;

		this.$element = $(element);
		var searchDOM = this.$element.find(".ui-table-search").html();
		this.$element.html(tpl);
		this.$element.find(".ui-table-search-content").html(searchDOM);

		// 设置高度
		var height = this.options.height || 500;
		this.$element.find(".ui-table-content").height(height);

		this.columns = this.options.columns;      // 列
		this.rowData = [];                         // 数据
		this.dataOptions = {
			pageIndex: (options.pageIndex || 1),                       // 页索引
			pageSize: (options.pageSizeNum || 20),                       // 页尺寸
			pageCount: 1,                       // 总页数
			total: 0,                            // 总记录数
			sortName: "",                  // 排序字段
			sortType: ""                // 排序类型
		};

		// 设置自定义每页条数
		if(this.options.pageSize){
			var html = ""
			_.each(this.options.pageSize, function(num){
				html += "<option>" + num + "</option>";

			});
			this.dataOptions.pageSize = this.options.pageSize[0];
			this.$element.find(".table-pagesize").html(html);

		}



		// 初始化列
		var colidNum = 0;
		_.each(this.columns, function (col, i) {
			var defaultCol = defaultColumn(col.type);
			_.extend(defaultCol, col);
			defaultCol.sortProperty = (defaultCol.sortProperty == "") ? defaultCol.property : defaultCol.sortProperty;
			if (defaultCol.property != "") {
				defaultCol.id = defaultCol.property;
			} else {
				defaultCol.id = "col" + colidNum;
				colidNum++;
			}
			defaultCol.num = i;
			this.columns[i] = defaultCol;
		}, this);

		// 合并本地缓存
		this.localKey = options.localKey;                         // 本地存储的Key
		if (this.localKey != undefined && this.localKey != "" && localStorage.getItem(this.localKey)) {

			var column = $.parseJSON(localStorage.getItem(this.localKey));
			if (_.isObject(column)) {
				this.setColumns(column);
//                this.columns = columns;
			}

		}


		// 渲染列头
		this.renderColumns();
		this.setFooter();



		// 事件

		this.$element.find(".ui-table-foot button.table-nextpage").on('click', $.proxy(this.next, this));                             // 下一页
		this.$element.find(".ui-table-foot button.table-prevpage").on('click', $.proxy(this.previous, this));
		this.$element.find(".ui-table-foot select.table-pagesize").on('change', $.proxy(this.pagesizeChanged, this));
		this.$element.find(".ui-table-foot input.table-pageindex").on('change', $.proxy(this.pageChanged, this));
		this.$element.find(".ui-table-foot input.table-pageindex").on('keydown', $.proxy(this.pageChanged, this));
		this.$element.find(".ui-table-foot form").on("submit", function () {
			return false;
		})

		this.$element.find(".ui-table-search i.icon-cog").on('click', function () {
			// 渲染设置列头弹出框
			self.renderColumnModal();
			self.$element.find(".ui-table-setcolumnmodal").modal();

		});
		// 设置列头
		this.$element.find(".table-setcolumn-button").on("click", function () {
//            var $selectColumn = self.$element.find(".ui-table-setcolumnmodal :checked");
//            if ($selectColumn.length == 0) {
//                $.msgGrowl({
//                    type: 'error', title: '设置显示列', text: '至少选择一列'
//                });
//                return;
//            }
			var column = {};
			var isChecked = 0;
			self.$element.find(".ui-table-setcolumnmodal :checkbox").each(function (index, selCol) {

				var $col = $(selCol);
				column[$col.attr("data-id")] = {
					isShow: $col.prop("checked"),
					num: index
				}
				if ($col.prop("checked")) {
					isChecked++;
				}
//                var column = {
//                    property: $col.attr("data-property"),
//                    sortProperty: $col.attr("data-sortProperty"),
//                    label: $col.attr("data-label"),
//                    type: $col.attr("data-type"),
//                    sortable: $col.attr("data-sortable"),
//                    commandName: $col.attr("data-commandname"),
//                    widthClass: $col.attr("data-widthclass"),
//                    class: $col.attr("data-class"),
//                    isShow: $col.prop("checked"),
//                    title: $col.attr("data-title")
//
//                }
//                self.columns.push(column);
			});
			if (isChecked == 0) {
				$.msgGrowl({
					type: 'error', title: '设置显示列', text: '至少选择一列'
				});
				return;
			}

			if (self.localKey != undefined && self.localKey != null && self.localKey != "") {
				localStorage.setItem(self.localKey, $.toJSON(column));
			}

			// 这段代码放在这里说实话有点唐突,按理组件应该和业务分离的
			// 不过我没有想到一个比较好的方法,本来想只保存到localStorage中,然后监听localStorage的事件,
			// 可是发现,在本页面是无法触发localStorage事件的
			// 当这个组件要移植到别的项目中,这里要修改 --by hmc 2013-8-8
			var ajaxData = {};
			ajaxData[self.localKey] = column;
			$.post(
				"/formular/menuSave.do",
				$.toJSON(ajaxData)
			);
			//----------------------------------------------------------------------------

			self.setColumns(column);
			self.renderColumns();
			self.renderRow();

			self.$element.find(".ui-table-setcolumnmodal").modal("hide");
		});

		this.$element.find(".table-setcolumnClose-button").on("click", function () {
			self.$element.find(".ui-table-setcolumnmodal").modal("hide");
		});
		// 滚动内容
		this.$element.find(".ui-table-content").on("scroll", function () {
			self.$element.find(".ui-table-header").scrollLeft($(this).scrollLeft());
		});


		// 展开
		var expand = function(){
			if(self.options.expandType == "collapse"){
				self.$element.find(".ui-table-header").hide();
				self.$element.find(".ui-table-content").hide();
				self.$element.find(".ui-table-foot").hide();

			}else{
				self.$element.find(".ui-table-header").show();
				self.$element.find(".ui-table-content").show();
				self.$element.find(".ui-table-foot").show();
			}
		}

		// 如果允许展开
		if(this.options.isExpand == true){
			this.options.expandType = "collapse";
			this.$element.find(".ui-table-search").css("cursor","pointer").on('click', function(event){

				// 因为列头内部的button等的click事件也会触发这个,所以排除掉
				var eventName = event.target.nodeName.toLowerCase();
				if(eventName == "button" || eventName == "input" || eventName == "select" || eventName == "i"){
					return;
				}

				if(self.options.expandType == "collapse"){
					self.options.expandType = "expand";
					expand();
					self.setBodyWidth();
				}else{
					self.options.expandType = "collapse";
					expand();
				}


			});
		}
		expand();

	};

	Datagrid.prototype = {

		constructor: Datagrid,

		renderColumns: function () {

			this.renderHeader();
			this.setBodyWidth();


//            this.setBodyWidth();
		},
		/**
		 * 根据传过来的的列和this.columns合并
		 */
		setColumns: function (column) {
			_.each(this.columns, function (col) {
				var c = column[col.id];
				if(c != undefined){
					col.isShow = c.isShow;
					col.num = c.num;
				}
			});

			this.columns = _.sortBy(this.columns, function(c){
				return c.num;
			});
		},
		/**
		 * 在动态列的时候更新列
		 * @param column
		 */
		editColumns: function(column){
			this.columns = column;

			// 这段代码有重复,再说把 -- by hmc 2013-10-12
			var colidNum = 0;
			_.each(this.columns, function (col, i) {
				var defaultCol = defaultColumn(col.type);
				_.extend(defaultCol, col);
				defaultCol.sortProperty = (defaultCol.sortProperty == "") ? defaultCol.property : defaultCol.sortProperty;
				if (defaultCol.property != "") {
					defaultCol.id = defaultCol.property;
				} else {
					defaultCol.id = "col" + colidNum;
					colidNum++;
				}
				defaultCol.num = i;
				this.columns[i] = defaultCol;
			}, this);
			this.renderColumns();
		},
		renderHeader: function () {
			var self = this;


			var html = THTemplate({
				columns: this.columns
			});
			//html = html.replace(/[\r\n\s]/g, "");
			self.$element.find(".ui-table-header thead tr").html(html);
			this.$element.find("th.sortable").on("click", $.proxy(this.headerClicked, this));   // 排序
			this.$element.find(".ui-table-header input[type=checkbox]").on("click", function (e) {
				e.stopPropagation();
				var isChecked = this.checked;
				self.$element.find(".ui-table-content :checkbox").each(function (checkbox) {
					this.checked = isChecked;
				});
				if (isChecked) {
					self.$element.find(".ui-table-content tr").addClass("info");
				} else {
					self.$element.find(".ui-table-content tr").removeClass("info");
				}
			});

		},
		/* 设置body的宽度 */
		setBodyWidth: function () {
			var self = this;
			setTimeout(function () {
				var width = self.$element.find(".ui-table-header-content table").width();
				// 当表格时displa:none的时候宽度是取不到的
				if (width == 0) {
					self.$element.css({ position: "absolute", visibility: "hidden", display: "block" });
					width = self.$element.find(".ui-table-header-content table").width();
					self.$element.css({ position: "", visibility: "", display: "" });
//                    _.each(self.columns,function(col){
//                        if(col.type == "checkbox"){
//                            width += 18;
//                        }else if(col.width == undefined){
//                            width += 200 + 16;
//                        }else{
//
//                            width += Number(col.width.split("px")[0]) + 16;
//                        }
//
//                    });
				}
				self.$element.find(".ui-table-content table").width(width);
			}, 100);

		},
		/* 渲染设置列头弹出框 */
		renderColumnModal: function () {
			var self = this;


			var html = setColumnTemplage({
				columns: this.columns
			});

			self.$element.find(".ui-table-setcolumnmodal .modal-body").html(html);
			self.$element.find(".ui-table-setcolumnmodal .modal-body ul").sortable();

		},
		/* 更新列头 */
		updateColumns: function ($target, direction) {
			var className = (direction === 'asc') ? 'icon-chevron-up' : 'icon-chevron-down';
			this.$element.find('.ui-table-header i').remove();
			this.$element.find('.ui-table-header th').removeClass('sorted');
			$('<i>').addClass(className + " sortico").appendTo($target.find(".ui-table-th"));
			$target.addClass('sorted');
		},

		/**
		 * 重新刷新数据
		 */
		renderData: function () {
			// 我记得这个属性是后面加的,不过忘记为什么加了,现在测试提了 1317号bug,我先注释吧 --by hmc 2013-9-13
			// 这个语句我还是打开了,如果点"查询"需要回滚到第一页的调用这个方法,如果在修改,删除后应该调用 reloadData 方法 -- by hmc 2013-9-22
			this.dataOptions.pageIndex = 1;
			this.reloadData();
		},
		/* 渲染行 */
		renderRow: function () {
			var self = this;
			var rowHTML = '';
			this.setBodyWidth();
			var htmlData = {
				rows: []
			};

			_.each(self.rowData, function (row, i) {
				var cols = [];

				_.each(self.columns, function (column) {
					var col = _.clone(column);
					col.rowIndex = i;


					if(column.valueData == undefined || column.valueData == null){
						if(column.type == "data"){
							col.valueData = row[column.property];
							col.titleData = row[column.property];

						}else if(column.type == "color"){
							col.valueData = row[column.property];
						}else{
							col.valueData = column.label;
							col.titleData = column.label;
							col.commandStyle = "cursor:pointer;";
						}

					}else{
						// 自定义显示
						var columnData =  column.valueData(row);

						col.valueData =  columnData.valueData;
						//2014-12-30  增加颜色自定义列的显示内容功能 ----lhl
						col.addInputData =  columnData.addInputData;
						//2014-12-30  ↑ ↑ ↑ ↑ ↑ ↑ ↑----lhl
						col.titleData = columnData.titleData;
						col.isReadonly = columnData.isReadonly;
						col.commandName = columnData.commandName;


						if(col.type == "command"){
							if(col.isReadonly == true){
								col.commandName = "";
								col.commandStyle = "cursor:default;color:#333;text-decoration:none;";
							}else{
								col.commandStyle = "cursor:pointer; " + columnData.css;
							}

						}else{
							col.style = columnData.css;
						}

					}

					cols.push(col);

				});
				htmlData.rows.push(cols);
			});
			var html = TDTemplate(htmlData);
			this.$element.find(".ui-table-content .load-view").remove();


			if ($.trim(html) == "") {
				html = "<tr><td style='boder: 0px;'></td></tr>";
				this.$element.find(".ui-table-content div.NoData").show();
			}
			//html = html.replace(/[\r\n\s]/g, "");

			this.$element.find(".ui-table-content tbody").html(html);

			// checkbox列
			self.$element.find(".ui-table-header :checkbox").each(function () {
				this.checked = false;
			})
			self.$element.find(".ui-table-content input[type=checkbox]").on("click", function (event) {
				event.stopPropagation();
				if (this.checked) {
					$(this).parents("tr").addClass("info");
				} else {
					$(this).parents("tr").removeClass("info");
				}
			});
			// command列
			self.$element.find(".ui-table-content a.command").click(function (event) {
				event.stopPropagation();
				var commandName = $(this).data("command_name");
				var index = $(this).attr("data-index");
				var property = $(event.target).parents("td").attr("data-property");
				var label =   $(event.target).parents("td").attr("data-label");
				var parameters = [];
				parameters.push(self.rowData[index]) ;
				parameters.push(property);
				parameters.push(label);

				self.$element.trigger(commandName, parameters);
			});

			// 在行上面单击
			var trs = self.$element.find(".ui-table-content tr");
			trs.on("click", function (event) {
				trs.removeClass("info");
				$(".ui-table-content input[type=checkbox]").prop("checked", false);

				$(this).addClass("info");
				$(this).find("input[type=checkbox]").prop("checked", true);

			});
			trs.find('a').on("click", function (event) {
				trs.removeClass("info");
				$(".ui-table-content input[type=checkbox]").prop("checked", false);

				$(this).parent().parent().parent().parent().addClass("info");
				$(this).parent().parent().parent().parent().find("input[type=checkbox]").prop("checked", true);

			});

			// 在TD上面单击
			var tds = self.$element.find(".ui-table-content td");
			tds.on("click", function (event) {
				tds.removeClass("light");
				$(event.currentTarget).parent().addClass("info");
				var tdClassName = $(event.currentTarget).find(
					".ui-table-td-content").attr("data-property");
				var allTds = self.$element
					.find(
						".ui-table-content [data-property="
							+ tdClassName + "]").parent().parent();
				allTds.addClass("light");
			});

			self.$element.trigger('loaded', self.rowData);


		},
		/* 渲染页脚 */
		setFooter: function () {
			var $footer = this.$element.find(".ui-table-foot");
			if(this.options.isPage == false){
				$footer.find(".form-inline").hide();
			}else{
				$footer.find(".form-inline").show();
				// 上一页按钮
				if (this.dataOptions.pageIndex > 1) {
					$footer.find(".table-prevpage").removeAttr("disabled")
				} else {
					$footer.find(".table-prevpage").attr("disabled", "disabled")
				}
				// 下一页按钮
				if (this.dataOptions.pageIndex < this.dataOptions.pageCount) {
					$footer.find(".table-nextpage").removeAttr("disabled")
				} else {
					$footer.find(".table-nextpage").attr("disabled", "disabled")
				}
				// 页总数
				$footer.find(".table-pagescount").text(this.dataOptions.pageCount);
				// 总记录数
				$footer.find(".table-total").text(this.dataOptions.total);
				// 页索引
				$footer.find(".table-pageindex").val(this.dataOptions.pageIndex);
				// 每页Size
				$footer.find(".table-pagesize").val(this.dataOptions.pageSize);
			}





		},

		/* 加载时的进度条 */
		placeholderRowHTML: function () {
			return "<div class='load-view'><i class='icon-spinner icon-spin icon-4x'></i></div>";
		},
		/* 排序 */
		headerClicked: function (e) {
			var $target = $(e.target).parents("th");
			if (!$target.hasClass('sortable')) return;

			var direction = this.dataOptions.sortType;
			var sort = this.dataOptions.sortName;
			var property = $target.attr('data-sortproperty');

			if (sort === property) {
				this.dataOptions.sortType = (direction === 'asc') ? 'desc' : 'asc';
			} else {
				this.dataOptions.sortType = 'asc';
				this.dataOptions.sortName = property;
			}

			this.dataOptions.pageIndex = 1;
			this.updateColumns($target, this.dataOptions.sortType);
			this.reloadData();
		},
		/* 切换每页总数 */
		pagesizeChanged: function (e) {
			this.dataOptions.pageSize = parseInt($(e.target).val());
			this.dataOptions.pageIndex = 1;
			this.reloadData();
		},

		/* 修改页索引 */
		pageChanged: function (e) {
			e.stopPropagation();
			if ((e.type == "keydown" && e.keyCode == 13) || e.type == "change") {
				var pageRequested = parseInt($(e.target).val(), 10);
				pageRequested = (isNaN(pageRequested)) ? 1 : pageRequested;
				var maxPages = this.dataOptions.pageCount;
				if (pageRequested <= maxPages && pageRequested >= 1) {
					this.dataOptions.pageIndex = pageRequested;
				} else if (pageRequested > maxPages) {
					this.dataOptions.pageIndex = maxPages;
				} else if (pageRequested < 1) {
					this.dataOptions.pageIndex = 1;
				}

				this.reloadData();
			}


		},

		/* 上一页 */
		previous: function () {
			this.dataOptions.pageIndex--;
			this.reloadData();
		},
		/* 下一页 */
		next: function () {
			this.dataOptions.pageIndex++;
			this.reloadData();
		},
		/*
		 获取选中列的数据
		 */
		getSelectedRow: function () {
			var selectedData = [];
			var self = this;
			this.$element.find(".ui-table-content :checked").each(function (index, el) {
				selectedData.push(self.rowData[$(this).attr("data-index")]);
			});
			return selectedData;
		},
		/* 得到所有数据 */
		getRowData: function () {
			return this.rwoData;
		},
//        /* 重置列 */
//        reloadColumn: function () {
//            this.columns = this.options.dataSource.columns();
//            this.$colheader.html("");
//            this.renderColumns();
//            this.reloadData();
//        },
		/* 重置数据 */
		reloadData: function () {
			if(this.isloading == true){
				return;
			}
			this.isloading = true;
			var self = this;

			// 绕圈圈
			this.$element.find(".ui-table-content tbody tr").remove();
			if (this.$element.find(".ui-table-content .load-view").length == 0) {
				this.$element.find(".ui-table-content").append(this.placeholderRowHTML());
			}
			this.$element.find(".ui-table-content div.NoData").hide();

			var callback = function(data){
				// 不保持保持原状
				if (data != "keep") {
					data = data || {
						data: [],
						pageIndex: 1,
						pageCount: 1,
						total: 0
					};

					self.rowData = data.data;

					self.dataOptions.pageIndex = data.pageIndex;
					self.dataOptions.pageCount = data.pageCount;
					if(Number(self.dataOptions.pageCount) == 0){
						self.dataOptions.pageCount = 1;
					}
					self.dataOptions.total = data.total;
				}

				// 当前页大于总页数就再查一次上一页的数据    --by hmc 2013-9-24
				if(self.dataOptions.pageIndex > self.dataOptions.pageCount && self.dataOptions.pageIndex > 1){
					self.dataOptions.pageIndex = Number(self.dataOptions.pageIndex) - 1;
					self.options.dataSource.data(self.dataOptions, callback);
				}else{
					// 渲染行
					self.setBodyWidth();
					self.renderRow();
					self.setFooter();
				}
				self.isloading = false;




			}

			this.options.dataSource.data(this.dataOptions, callback);
		}
	};


	// DATAGRID PLUGIN DEFINITION

	$.fn.datagrid = function (option, value) {
		var methodReturn;

		var $set = this.each(function () {
			var $this = $(this);
			var data = $this.data('datagrid');
			var options = typeof option === 'object' && option;
			if (!data) {
				$this.data('datagrid', (data = new Datagrid(this, options)));
			}

			if (typeof option === 'string') {
				methodReturn = data[option](value);
			}

		});
		return (methodReturn === undefined) ? $set : methodReturn;
	};

	$.fn.datagrid.defaults = {
		dataOptions: { pageIndex: 1, pageSize: 20 },
		loadingHTML: '<div class="progress progress-striped active" style="width:50%;margin:auto;"><div class="bar" style="width:100%;"></div></div>',
		itemsText: '',
		itemText: 'item'
	};

	$.fn.datagrid.Constructor = Datagrid;

});
